/*
 * richtextedit.cpp
 *
 *  Created on: 5.3.2010
 *      Author: aahv
 */

#include "richtextedit.h"
#include "ui_richtextedit.h"

#include <QDebug>

RichTextEdit::RichTextEdit(QWidget *parent) :
        QWidget(parent),
        ui(new Ui::RichTextEdit),
        dialog(new AddLinkDialog(parent))
{
    ui->setupUi(this);

    connect(dialog, SIGNAL(showErrorNote(QString)), this, SIGNAL(showErrorNote(QString)));
    connect(dialog, SIGNAL(addLink(QString, QUrl)), this, SLOT(addLink(QString, QUrl)));
    connect(dialog, SIGNAL(finished(int)), this, SLOT(refocusEditor()));
}

RichTextEdit::~RichTextEdit()
{
    delete ui;
}

void RichTextEdit::setExplanationText(const QString& text) {
    ui->textEdit->SetExplanation(text);
}

void RichTextEdit::setText(const QString& text) {
    ui->textEdit->setText(text);
}

QString RichTextEdit::text() const {
    return ui->textEdit->text();
}

void RichTextEdit::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void RichTextEdit::reset() {
    ui->boldButton->setChecked(false);
    ui->italicButton->setChecked(false);
    ui->quoteButton->setChecked(false);
}

void RichTextEdit::on_boldButton_toggled(bool checked)
{
    insertTag("strong", checked);
}

void RichTextEdit::on_italicButton_toggled(bool checked)
{
    insertTag("em", checked);
}

void RichTextEdit::on_quoteButton_toggled(bool checked)
{
    insertTag("blockquote", checked);
}

void RichTextEdit::on_linkButton_clicked()
{
    ui->textEdit->clearFocus();
    dialog->setModal(true);
    if (dialog->isHidden()) {
        QSize parentSize = QApplication::desktop()->screenGeometry().size();
        dialog->setMinimumWidth((int)(parentWidget()->size().width() * 0.8));
        dialog->show();
        dialog->move((parentSize.width() - dialog->width()) / 2, (parentSize.height() - dialog->height()) / 2);
        dialog->activateWindow();
        dialog->setFocus();
    }
    else {
        dialog->raise();
        dialog->activateWindow();
        dialog->setFocus();
    }
}

void RichTextEdit::addLink(const QString &title, const QUrl &link) {
    ui->textEdit->insertText("<a href=\"" + link.toEncoded(QUrl::None) + "\">" + title + "</a>");
}

void RichTextEdit::refocusEditor() {
    activateWindow();
    ui->textEdit->setFocus();
}

void RichTextEdit::insertTag(const QString &tag, bool begin) {
    ui->textEdit->clearFocus();
    ui->textEdit->insertText(begin? "<" + tag + ">": "</" + tag + ">");
    ui->textEdit->setFocus();
}
